import store from '@/store'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const tabbar = { tabbar: () => import('@/components/app-tabbar') }

const UserProfile = () => import('@/views/user/profile')
const UserChat = () => import('@/views/user/chat')

const routes = [
  { path: '/', components: { default: () => import('@/views/home'), ...tabbar } },
  { path: '/question', components: { default: () => import('@/views/question'), ...tabbar } },
  { path: '/video', components: { default: () => import('@/views/video'), ...tabbar } },
  { path: '/user', components: { default: () => import('@/views/user'), ...tabbar } },
  { path: '/article', component: () => import('@/views/article') },
  { path: '/login', component: () => import('@/views/login') },
  { path: '/user/profile', component: UserProfile },
  { path: '/user/chat', component: UserChat }
]

const router = new VueRouter({
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  // 没登录却访问user下的路由
  if (!token && to.path.startsWith('/user')) {
    return next('/login?returnUrl=' + encodeURIComponent(to.fullPath))
  }
  // 其他情况放行
  next()
})

export default router
